﻿using Assets.Scripts.DL.Consts;
using Assets.Scripts.DL.Enemy.CommonEnemy;
using Assets.Scripts.DL.Mgrs;
using UnityEngine;

namespace Assets.Scripts.DL.Enemy.YaSuo {
	public class YasuoCommonAtk : CommonState<YasuoController> {
		public YasuoCommonAtk(YasuoController controller, StateEnum stateName) : base(controller, stateName) {
			_timer = _controller.StateData.AtkCdRecoder[StateName];

			//两个普攻范围相同冷却相同
			AddConditionToSelf(() => _controller.IsPlayerInAtkRange()
			&& _timer.Elapsed > _controller.Config.CommonAtkGap);
		}

		readonly Timer _timer;
		bool _sendDamage;
		//bool _animStart;

		Vector2 _atkOffset;
		float _range;
		int _damage;

		public override void Enter() {
			_controller.Player.GetComponent<PlayerController>().ShowDangerIcon();
			_controller.PlayAnim(StateName);
			_controller.Velocity = Vector2.zero;
			_controller.StateData.AtkOver = false;
			//_animStart = false;
			_sendDamage = false;

			_atkOffset = _controller.Config.AtkOff;
			_range = _controller.Config.AtkDis;
			_damage = _controller.Config.Damage;
			if (_controller.CurQCnt == 2) {
				AudioManager.Play(_controller.Voice2, AudioStr.HaSai, false);
			}
		}

		public override void Update() {
			if (!_sendDamage) {
				CheckDamage(ref _sendDamage);
			}
			if (_controller.IsAnimPlayOver()) {
				_controller.StateData.AtkOver = true;
			}
		}

		public override void Exit() {
			_timer.Reset();
			_controller.StateData.LastAtkTime.Reset();
		}

		void CheckDamage(ref bool dmgSend) {
			if (_controller.IsAnimPlayAt(0.75f)) {
				var ishit = _controller.CheckAtk(_atkOffset, _range, _damage);
				dmgSend = true;
				if (ishit) {
					_controller.CurQCnt++;
					//Debug.Log("Q中，音效，叠加次数");
					if (_controller.CurQCnt > 2) {
						_controller.CurQCnt = 0;
						AudioManager.Play(_controller.Voice1, AudioStr.HaSaiGi, false);

						//Debug.Log("风");
						var obj = ObjectPool.Instance.GetObject(ObjPoolStr.Wind);
						var dir = _controller.FaceDir;
						var off = _controller.WindOffset;
						var v = new Vector2(dir * _controller.WindFlySpeed, 0);
						var pos = _controller.transform.position + new Vector3(dir * off.x, off.y);
						obj.GetComponent<Wind>().Init(v, _controller.WindFlyTime, pos);
					}
				}
			}
		}
	}
}
